import { ref } from "vue";
import * as vant from "vant";
import { postAction } from "@/command/netTool";
import { useRouter } from 'vue-router';
import storeTool from '@/command/storeTool'
const { showFailToast, showSuccessToast } = vant;
export const useRequest = () => {
    const router = useRouter()
    const form = ref({
        phone: "",
        code: "",
    });

    const codeButtonText = ref("获取验证码");
    const getCode = () => {

    }
    const setCountdown = () => {
        let time: any;
        let num = 60;
        if (codeButtonText.value == '获取验证码') {
            time = setInterval(() => {
                if (num == 0) {
                    codeButtonText.value = '获取验证码'
                    clearInterval(time as any)
                } else {
                    num -= 1
                    codeButtonText.value = String(num)
                }
            }, 1000)
        }
    }

    const loadSuccessCallback = (res: any) => {
        if (res.errorMessage == "jsload_error") {
            showFailToast("短信获取失败");
            return;
        } else {
            postAction("/api/H5/controller/send", {
                phone: form.value.phone,
                ...res
            }).then(() => {
                showSuccessToast('短信发送成功')
                setCountdown()
            })
        }
    };

    const login = () => {
        // let res = {
        //     tokenValue: "3f141f32-c753-423d-82a0-1d259b013881",
        //     user: {
        //       address: "宁波市镇海区汇锦路18号",
        //       areaCode: "330211",
        //       areaName: "镇海区",
        //       countryCode: "330211003",
        //       countryName: "骆驼街道",
        //       entityLogo: "https://t7.baidu.com/it/u=4036010509,3445021118&fm=193&f=GIF",
        //       entityName: "主体",
        //       id: "4",
        //       isNewRecord: false,
        //       lat: "29.46",
        //       lng: "121.87",
        //       logo: "https://qfile.nongqibang.com/1675918606303_574.jpeg",
        //       name: "大户4",
        //       phone: "18397830144",
        //       productTypeId: "1631224471140159488",
        //       sex: "0",
        //       state: "1",
        //       userType: "1"
        //     }
        // }
        postAction('/api/H5/controller/phoneLogin', {
            phone: form.value.phone,
            yzm: form.value.code
        })
            .then((e) => {
                const history = localStorage.getItem('historyUrl')
                localStorage.setItem('userInfo', JSON.stringify(e.user))
                storeTool.auth.set({
                    access_token: e.tokenValue
                })
                history ? router.replace(history as any) : router.push("/my")
            })
    }
    return {
        form,
        getCode,
        codeButtonText,
        loadSuccessCallback,
        login,
        back: router.back
    }
}